from datetime import datetime

from flask import Blueprint, render_template, request, jsonify, session
from flask_login import login_required
from sqlalchemy import and_
from werkzeug.security import generate_password_hash

from applications.common import curd
from applications.common.curd import model_to_dicts, enable_status, disable_status, get_one_by_id, enable_is_on_sale, \
    disable_is_on_sale
from applications.common.helper import ModelFilter
from applications.common.utils.getopenid import get_openid, token
from applications.common.utils.http import table_api, success_api, fail_api, wxuser_success_api, goods_api, \
    index_goods_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.exts import db
from applications.exts.cache import cache
from applications.models import Role, Power, User, Goods, Classify
from applications.models.wx_user import WxUser
from applications.schemas import RoleOutSchema, PowerOutSchema2, WxUserOutSchema, GoodsOutSchema, WxUClassifyOutSchema
from applications.common.utils import upload as upload_curd

goods = Blueprint('goods', __name__, url_prefix='/goods')


# 商品管理
@goods.route('/')
@login_required
# flask 实现 Authorization请求报头认证
# @authorize("wxuser:role:main", log=True)
def main():
    return render_template('goods/goodsmain.html')


#   用户分页查询
@goods.route('/data')
@login_required
# @authorize("admin:user:main", log=True)
def data():
    # 获取请求参数
    gname = xss_escape(request.args.get('gname', type=str))
    gnum = xss_escape(request.args.get('gnum', type=str))
    # 查询参数构造
    mf = ModelFilter()
    if gname:
        mf.contains(field_name="gname", value=gname)
    if gnum:
        mf.contains(field_name="gnum", value=gnum)
    # if dept_id:
    #     mf.exact(field_name="dept_id", value=dept_id)
    # orm查询

    # 使用分页获取data需要.items
    goods = Goods.query.filter(mf.get_filter(model=Goods)).layui_paginate()
    count = goods.total
    # 返回api
    return table_api(data=model_to_dicts(schema=GoodsOutSchema, data=goods.items), count=count)


# 商品增加
@goods.route('/add')
@login_required
# @authorize("admin:user:add", log=True)
def add():
    classify = Classify.query.all()
    return render_template('goods/add.html', classify=classify)


@goods.route('/upload', methods=["POST"])
@login_required
def upphoto():
    if 'file' in request.files:
        photo = request.files['file']
        mime = request.files['file'].content_type
        print(photo)
        file_url = upload_curd.upfile(file=photo, flag=0)
        print(file_url)
        file_url = request.host_url + file_url
        print('file_url:', file_url)
        res = {
            "msg": "上传成功",
            "code": 0,
            "success": True,
            "data":
                {"src": file_url}
        }
        return jsonify(res)
    return fail_api()


# 后台add商品
@goods.route('/addgoods', methods=["POST"])
@login_required
# @authorize("admin:user:add", log=True)
def addgoods():
    req_json = request.json

    print('req_json:', req_json)

    gname = xss_escape(req_json.get('gname'))
    price = xss_escape(req_json.get('price'))
    gname = xss_escape(req_json.get('gname'))

    gtypes = xss_escape(req_json.get('gtypes'))

    gnum = xss_escape(req_json.get('gnum'))

    isnew = xss_escape(req_json.get('isnew'))

    if isnew == 'on':
        isnew = 1
    else:
        isnew = 0
    is_on_sale = xss_escape(req_json.get('is_on_sale'))
    if is_on_sale == 'on':
        is_on_sale = 1
    else:
        is_on_sale = 0
    ishot = xss_escape(req_json.get('ishot'))

    if ishot == 'on':
        ishot = 1
    else:
        ishot = 0

    desc = xss_escape(req_json.get('desc'))
    gphoto = xss_escape(req_json.get('file'))

    good = Goods()
    good.gname = gname
    good.gnum = gnum
    good.price = price
    good.isnew = isnew
    good.is_on_sale = is_on_sale
    good.content = desc
    good.gphoto = gphoto
    good.classifyid = int(gtypes)
    good.iscommon = ishot

    db.session.add(good)
    db.session.commit()
    return success_api(msg='添加成功')
    # code = xss_escape(req_json.get('code'))
    # userInfo = xss_escape(req_json.get('userInfo'))
    # print(code,userInfo)

    # code = req_json.get('code')
    # userInfo = req_json.get('userInfo')
    # username = userInfo.get('nickName')
    # avatarUrl = userInfo.get('avatarUrl')
    # openid = get_openid(code)
    # print(code, username, avatarUrl, openid)
    # wxtokens = token(code)
    # a = req_json.get("roleIds")
    # username = xss_escape(req_json.get('username'))
    # password = xss_escape(req_json.get('password'))
    # phone = xss_escape(req_json.get('phone'))
    # file = xss_escape(req_json.get('file'))
    #
    # wxuser = WxUser()
    # wxuser.username = username
    # wxuser.phone = phone
    # wxuser.set_password(password)
    # wxuser.avatar = file
    # db.session.add(wxuser)
    # db.session.commit()
    # # role_ids = a.split(',')
    #
    # if not username or not real_name or not password:
    #     return fail_api(msg="账号姓名密码不得为空")
    # #
    # if bool(User.query.filter_by(username=username).count()):
    #     return fail_api(msg="用户已经存在")
    # wxuser = WxUser(username=username, openid=openid, avatar=avatarUrl, enable=1)
    # user.set_password(password)
    # db.session.add(wxuser)
    # db.session.commit()
    # roles = Role.query.filter(Role.id.in_(role_ids)).all()
    # for r in roles:
    #     user.role.append(r)

    # wxuser_success_api(errno: int = 0, user:dict = {}, token:str = '', msg:str = ''):


# 上架商品
@goods.route('/enable', methods=["PUT"])
@login_required
# @authorize("admin:user:edit", log=True)
def enable():
    _id = request.json.get('gid')
    print('_id:',_id)
    if _id:
        res = enable_is_on_sale(model=Goods, id=_id)
        if not res:
            print(1)
            return fail_api(msg="出错啦")
        print(2)
        return success_api(msg="上架成功")
    return fail_api(msg="数据错误")


# 下架商品
@goods.route('/disable', methods=["PUT"])
@login_required
# @authorize("admin:user:edit", log=True)
def dis_enable():
    _id = request.json.get('gid')
    print('_id:', _id)
    if _id:
        res = disable_is_on_sale(model=Goods, id=_id)

        if not res:
            print(1)
            return fail_api(msg="出错啦")
        print(2)
        return success_api(msg="下架成功")
    return fail_api(msg="数据错误")


# 删除用户
@goods.route('/remove/<int:id>', methods=["DELETE"])
@login_required
# @authorize("admin:user:remove", log=True)
def delete(id):
    # user = User.query.filter_by(id=id).first()
    # user.role = []

    # res = User.query.filter_by(id=id).delete()

    res = Goods.query.filter_by(id=id).delete()

    db.session.commit()
    print('res:', res)
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


# 批量删除
@goods.route('/batchRemove', methods=["DELETE"])
@login_required
# @authorize("admin:user:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        # wxuser = WxUser.query.filter_by(id=id).first()
        # user.role = []

        res = Goods.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")


#  编辑商品
@goods.route('/edit/<int:id>/')
@login_required
# @authorize("admin:user:edit", log=True)
def edit(id):
    goods = curd.get_one_by_id(Goods, id)

    classify = Classify.query.filter(Classify.classifyid == goods.classifyid).first()
    classifys = Classify.query.filter().all()
    # print(classify.gname)
    # roles = Role.query.all()
    # checked_roles = []
    # for r in user.role:
    #     checked_roles.append(r.id)

    return render_template('goods/edit.html', goods=goods, classify=classify, classifys=classifys)


# 编辑商品put
@login_required
@goods.route('/update', methods=["PUT"])
def update():
    req_json = request.json
    print(req_json)

    id = xss_escape(req_json.get("id"))
    gname = xss_escape(req_json.get('gname'))
    price = xss_escape(req_json.get('price'))
    gtypes = xss_escape(req_json.get('gtypes'))
    gnum = xss_escape(req_json.get('gnum'))
    desc = xss_escape(req_json.get("desc"))
    gphoto = xss_escape(req_json.get("file"))
    isnew = xss_escape(req_json.get("isnew"))
    if isnew == 'on':
        isnew = 1
    else:
        isnew = 0
    is_on_sale = xss_escape(req_json.get('is_on_sale'))
    if is_on_sale == 'on':
        is_on_sale = 1
    else:
        is_on_sale = 0
    ishot = xss_escape(req_json.get('ishot'))

    if ishot == 'on':
        ishot = 1
    else:
        ishot = 0

    good = Goods.query.get(id)
    if good:
        good.gname = gname
        good.gnum = gnum
        good.price = price
        good.isnew = isnew
        good.is_on_sale = is_on_sale
        good.content = desc
        good.gphoto = gphoto
        good.classifyid = gtypes
        good.iscommon = ishot
        db.session.commit()

    # # role_ids = a.split(',')
    # wxu = WxUser.query.filter_by(id=id).first()
    # if wxu:
    #     wxu.username = username
    #     wxu.avatar = file
    #     wxu.phone = phone
    #     wxu.password_hash = generate_password_hash(password)
    #     # User.query.filter_by(id=id).update({'username': username, 'realname': real_name, 'dept_id': dept_id})
    #     # wxu = WxUser.query.filter_by(id=id).first()
    #     #
    #     # roles = Role.query.filter(Role.id.in_(role_ids)).all()
    #     # u.role = roles
    #     #
    #     db.session.commit()

    return success_api(msg="更新成功")


# ==========分类=======
# 添加分类
@goods.route('/classifyadd')
@login_required
def classifyadd():
    classify = Classify.query.all()
    return render_template('goods/classify_add.html', classify=classify)


@goods.route('/addclassify', methods=["POST"])
@login_required
def addclassify():
    req_json = request.json
    classifyname = xss_escape(req_json.get('classifyname'))

    classify = Classify.query.filter(Classify.gname == classifyname).first()
    if classify:
        return fail_api(msg='分类已存在')
    else:
        cl = Classify()
        cl.gname = classifyname
        db.session.add(cl)
        db.session.commit()
        return success_api(msg='分类添加成功')


@goods.route('/removeclassify/<int:id>', methods=["DELETE"])
@login_required
def classifydelete(id):
    res = Classify.query.filter_by(classifyid=id).delete()

    db.session.commit()
    print('res:', res)
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")

# ========wx分类和商品获取==========

@goods.route('/menulist', methods=["POST", "GET"])
def menulist():
    goods = cache.get(f"goods")
    classifys = cache.get(f"classifys")
    if goods and classifys:
        print('goods:', goods)
        print('redis')
        return goods_api(classify=classifys, goods=goods, msg='获取成功')
    else:
        print('mysql')
        classify = Classify.query.all()
        goodslist = Goods.query.filter(Goods.is_on_sale == 1).all()
        classifys = model_to_dicts(schema=WxUClassifyOutSchema, data=classify)
        goods = model_to_dicts(schema=GoodsOutSchema, data=goodslist)
        print('goods:', goods)
        cache.set(f'goods', goods, timeout=60)
        cache.set(f'classifys', classifys, timeout=60)
        # return table_api(data=model_to_dicts(schema=WxUserOutSchema, data=wxuser.items), count=count)
        return goods_api(classify=classifys, goods=goods, msg='获取成功')


# 获取新产品
@goods.route('/getnewgoodslist', methods=["POST", "GET"])
def Getnewgoodslist():
    goodslist = Goods.query.filter(and_(Goods.is_on_sale == 1, Goods.isnew == 1)).all()
    goods = model_to_dicts(schema=GoodsOutSchema, data=goodslist)
    return index_goods_api(goods=goods, msg='获取成功')


# 获取热卖产品
@goods.route('/gethotgoodslist', methods=["POST", "GET"])
def Gethotgoodslist():
    goodslist = Goods.query.filter(and_(Goods.is_on_sale == 1, Goods.iscommon == 1)).all()
    goods = model_to_dicts(schema=GoodsOutSchema, data=goodslist)
    return index_goods_api(goods=goods, msg='获取成功')
